//
//  HCUserAccountViewModel.swift
//  新浪微博
//
//  Created by fanhoucheng on 16/9/26.
//  Copyright © 2016年 fanhoucheng. All rights reserved.
//

import UIKit

private let path = (NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last! as NSString).appendingPathComponent("account.plist")

class HCUserAccountViewModel: NSObject {
    
    //单例对象
    static var sharedUserAccountViewModel: HCUserAccountViewModel = HCUserAccountViewModel()
    
    var userAccount: HCUserAccount? {
        didSet {
            //一旦给用户赋值的时候就保存url
            let urlString = userAccount?.avatar_large ?? ""
            iconURL = URL(string: urlString)
            print(iconURL)
            print("😄😄😄😄😄😄😄😄😄😄😄😄😄😄😄")
        }
    }
    
    var iconURL: URL?
    
    //计算型属性来判断是否曾经登录过
    var userLogin: Bool {
        if userAccount?.access_token != nil  && isExpires {
            return true
        }
        return false
    }
    
    var isExpires: Bool {
        
        if ComparisonResult.orderedDescending == userAccount?.expires_date?.compare(Date()) {
            return true
        }
        return false
    }
    
    override init() {
        super.init()
        self.userAccount = NSKeyedUnarchiver.unarchiveObject(withFile: path) as? HCUserAccount
        let urlString = userAccount?.avatar_large ?? ""
        iconURL = URL(string: urlString)
    }
    
    
    func loadAccessToken(code: String,finished: @escaping (Bool) -> ()) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parameters = ["client_id" : client_id,
                          "client_secret" : client_secret,
                          "grant_type" : "authorization_code",
                          "code" : code,
                          "redirect_uri" : redirect_uri]
        
        HMNetworkTools.sharedTools.request(method: .POST, urlString: urlString, parameters: parameters) { (responseObject, error) in
            
            if error != nil {
                finished(false)
                return
            }
            /* responseObject中打印出的是下面的
             "access_token" = "2.00tDCJ1CegB_lB336d3456fbSq2_DE";
             "expires_in" = 104886;
             "remind_in" = 104886;
             uid = 2129945265;
             */
            
            self.loadUserInfo(dict: responseObject as! [String: Any],finished: finished)
            
        }
    }
    
    func loadUserInfo(dict: [String: Any],finished: @escaping (Bool) -> ()) {
        let urlString = "https://api.weibo.com/2/users/show.json"
        let access_token = dict["access_token"]!
        let uid = dict["uid"]!
        
        let parameters = ["access_token":access_token,
                          "uid":uid]
        
        HMNetworkTools.sharedTools.request(method: .GET, urlString: urlString, parameters: parameters) { (responseObject, error) in
            //获取用户信息
            if error != nil {
                finished(false)
                return
            }
            var userInfoDict = responseObject as! [String: Any]
            
            //合并字典
            for keyValues in dict {
                userInfoDict[keyValues.key] = keyValues.value
            }
            //字典转模型
            let userAccount = HCUserAccount(dict: userInfoDict)
            
            //第一次登陆不从沙河获取数据,所以
            self.userAccount = userAccount
            //保存到沙河中
            self.saveUserAccount(userAccount: userAccount)
            finished(true)
        }
    }
    
    func saveUserAccount(userAccount: HCUserAccount) {
        //保存到沙河中
        
        
        //保存
        NSKeyedArchiver.archiveRootObject(userAccount, toFile: path)
        
        
    }
    
}
